package com.wonders.framework.util;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.wonders.framework.constant.DateConstant;
import com.wonders.framework.exception.FrameworkException;

/**
 * JSON工具
 * 
 * @author WuBin
 * 
 */
public class JsonUtil {

	/**
	 * 对象转JSON
	 * 
	 * @param object
	 *            对象
	 * @return JSON
	 */
	public static String toJson(Object object) {
		ObjectMapper mapper = new ObjectMapper();
		mapper.setDateFormat(DateConstant.DATE_FORMAT);
		try {
			return mapper.writeValueAsString(object);
		} catch (Exception e) {
			throw new FrameworkException("object转换为json失败", e);
		}
	}

	/**
	 * JSON转实体
	 * 
	 * @param <T>
	 * @param json
	 *            JSON
	 * @param clazz
	 *            类
	 * @return 实体
	 */
	public static <T> T toObject(String json, Class<T> clazz) {
		ObjectMapper mapper = new ObjectMapper();
		mapper.setDateFormat(DateConstant.DATE_FORMAT);
		try {
			return mapper.readValue(json, clazz);
		} catch (Exception e) {
			throw new FrameworkException("json转换为object失败", e);
		}
	}
}